import socket
import time
import sys
import tty
import termios

# 创建 socket 对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 定义服务器的 IP 地址和端口号
host = '192.168.35.117'  # 服务端的 IP 地址
port = 8080             # 服务端的端口

# 连接到服务器
try:
    client_socket.connect((host, port))
    print("已连接到服务器")
except Exception as e:
    print(f"连接失败: {e}")
    exit(1)

# 保存原始终端设置
old_settings = termios.tcgetattr(sys.stdin)

try:
    tty.setcbreak(sys.stdin.fileno())  # 设置为字符模式

    print("输入指令:")
    print("w - 前进")
    print("s - 后退")
    print("a - 停止")
    print("z - 站立")
    print("x - 蹲下")
    print("q - 退出")

    while True:
        # 获取键盘输入的单个字符
        char = sys.stdin.read(1)

        # 根据输入的字符构造不同的控制消息
        if char == 'w':
            message = "linear x: 0.5, angular z: 0.0\n"
        elif char == 's':
            message = "linear x: -0.5, angular z: 0.0\n"
        elif char == 'a':
            message = "linear x: 0.0 angular z: 0.0\n"
        elif char == 'z':
            message = "linear x: 0.0, angular z: 0.0, action: 1\n"
        elif char == 'x':
            message = "linear x: 0.0, angular z: 0.0, action: 0\n"
        elif char == 'q':
            print("退出程序")
            break
        else:
            print(f"无效输入: {char}")
            continue

        # 发送消息
        try:
            client_socket.sendall(message.encode('utf-8'))
            print(f"已发送消息: {message}")
        except BrokenPipeError:
            print("连接已断开，尝试重新连接...")
            # 尝试重新连接
            client_socket.close()
            client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            try:
                client_socket.connect((host, port))
                print("已重新连接到服务器")
            except Exception as e:
                print(f"重新连接失败: {e}")
                time.sleep(1)
                continue

except KeyboardInterrupt:
    print("\n客户端正在关闭...")
finally:
    # 恢复原始终端设置
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
    client_socket.close()
    print("连接已关闭")